package com.exercise.ThreadSynchronization.volatileMethod;

public class VolatileNonAtomicDemo {
    private volatile int counter = 0;

    public void increment() {
        counter++; // 非原子操作
    }

    public int getCounter() {
        return counter;
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileNonAtomicDemo demo = new VolatileNonAtomicDemo();

        // 创建100个线程，每个线程递增1000次
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                demo.increment();
            }
        };

        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(task);
            threads[i].start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("Final counter: " + demo.getCounter());
    }
}